#include "public.h"


struct	str_buffer_s
{
	char	*buf;
	int	len;
	int	alloc_bytes;
};



struct str_buffer_s	*str_new( )
{
	struct str_buffer_s *str;

	str = (struct str_buffer_s*)malloc(sizeof(*str));
	if( NULL == str ) 
		return NULL;

	str->buf		= NULL;
	str->len		= 0;
	str->alloc_bytes	= 0;

	return str;
}


void	str_free( struct str_buffer_s *str )
{
	if( NULL != str->buf )
		free( str->buf );
	
	free( str );
}


void	str_empty( struct str_buffer_s *str )
{
	str->len = 0;
}


int	str_alloc( struct str_buffer_s *str, const char *src, int src_len )
{
	int	alloc_bytes;

	alloc_bytes	= src_len + 1;
	if( alloc_bytes > str->alloc_bytes )
	{
		str->buf = realloc( str->buf, alloc_bytes );
		if( NULL == str->buf ) 
		{
			str->len = str->alloc_bytes = 0;
			return RET_ERR;
		}
		str->alloc_bytes = alloc_bytes;
	}

	memcpy( str->buf, src, src_len );
	str->len = src_len;
	str->buf[str->len] = '\0';
	
	return RET_OK;
}


int	str_append( struct str_buffer_s *str, const char *src, int src_len )
{
	int	alloc_bytes;

	alloc_bytes	= str->len + src_len + 1;
	if( alloc_bytes > str->alloc_bytes )
	{
		str->buf = realloc( str->buf, alloc_bytes );
		if( NULL == str->buf )
		{
			str->len = str->alloc_bytes = 0;
			return RET_ERR;
		}
		str->alloc_bytes = alloc_bytes;
	}
	memcpy( str->buf + str->len, src, src_len );
	str->len += src_len;
	str->buf[str->len] = '\0';

	return RET_OK;
}


int	str_getlen( struct str_buffer_s *str )
{
	return str->len;
}


char	*str_getbuf( struct str_buffer_s *str )
{
	return str->buf;
}



